package net.hserver.admin.system.utils;


import cn.hserver.plugin.web.context.HServerContextHolder;
import org.lionsoul.ip2region.xdb.Searcher;

import java.io.*;

public class IpUtil {
    private static Searcher ipSearcher;


    public static String getIp(String ip) {
        try {
            if (ipSearcher == null) {
                ipSearcher = Searcher.newWithBuffer(data());
            }
            return ipSearcher.search(ip);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String getIp() {
        return getIp(HServerContextHolder.getWebKit().httpRequest.getIpAddress());
    }

    private static byte[] data() {
        try {
            InputStream is = cn.hserver.plugin.web.util.IpUtil.class.getResourceAsStream("/ip2region/ip2region.xdb");
            try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = is.read(buffer)) != -1) {
                    byteArrayOutputStream.write(buffer, 0, bytesRead);
                }
                return byteArrayOutputStream.toByteArray();
            }
        } catch (IOException var6) {
            return null;
        }
    }

}
